const http = require('../../../utils/http.js')
const Base64 = require('../../../utils/base64.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgUrl: http.imgUrl,
        navBar: {
            title: '我的订单',
            btn: 'goBack'
        },
        nullData: {
            img: http.imgUrl + 'null_data_1.jpg',
            txt: '暂无订单'
        },
        order_list: [],
        star: [],
      payway:'5',
      orderMoney: true,
      showPayPwdInput: false,  //是否展示密码输入层
      pwdVal: '',  //输入的密码
      payFocus: true, //文本框焦点
    },

    /**
     * 返回
     */
    goBack() {
        http.goBack()
    },

    /**
     * 立即支付
     */
    goPay(e) {
        let that = this,
            balance = that.data.balance,
            price = e.currentTarget.dataset.price,
            order_no = e.currentTarget.dataset.orderno

        that.setData({
            payModal: {
                show: true,
                price: price,
                noBalance: balance >= Number(price) ? false : true,
                hide: 'hidePay',
                payWay: balance >= Number(price) ? '5' : '3',
                choosePayWay: 'choosePayWay',
                pay: 'pay'
            },
            order_no: order_no,
            pay_price: price,
            payWay: balance >= Number(price) ? '5' : '3'
        })
    },

    /**
     * 关闭立即支付
     */
    hidePay() {
        this.setData({
            payModal: {
                show: false
            }
        })
    },

    /**
     * 选择支付方式
     */
    choosePayWay(e) {
        let that = this,
            price = that.data.pay_price,
            balance = that.data.balance,
            payway = e.currentTarget.dataset.payway

        if (balance > Number(price)) {
            that.setData({
                payModal: {
                    show: true,
                    price: price,
                    noBalance: false,
                    hide: 'hidePay',
                    payWay: payway,
                    choosePayWay: 'choosePayWay',
                    pay: 'pay'
                },
                payway: payway
            })
        }
        console.log(payway)
    },

  hidePayLayer: function () {

    var val = this.data.pwdVal;

    this.setData({ showPayPwdInput: false, payFocus: false, pwdVal: val, orderMoney: true, }, function () {

    });

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });

    if (e.detail.value.length >= 6) {
      this.hidePayLayer();
      this.luck() //输入完密码后的方法调用
    }
  },



  luck() {
    console.log("请求支付接口")
    var url = 'Order_payOrder'
    var order_no = this.data.order_no
    var payway = this.data.payway
    var token = wx.getStorageSync('token')
    var title = this.data.pwdVal
    console.log(title)
    var pay_password = Base64.CusBASE64.encoder('UNO' + title + 'HACHA')
    console.log(pay_password)
    http._post(
      url,
      { token: token, order_no: order_no, type: payway, pay_password: pay_password },
      res => {
        var data = res.data
        //  console.log(data)
        wx.showToast({
          title: '支付成功',
          icon:"none",
          duration:3000,
          success:function(){
            wx.navigateTo({
              url: '/pages/course/soiDetail/soiDetailPay/soiDetailPaySuc/soiDetailPaySuc' 
            })
          }
        })
      }
    )
  },

  /**
   * 支付方法
   */
  pay() {
    var payway = this.data.payway
    var token = wx.getStorageSync('token')
    console.log(payway)
    console.log(token)
    // 余额支付
    if (payway === "3") {
      var url = 'Order_setMoney'
      http._post(
        url,
        { token: token },
        res => {
          var data = res.data
          console.log(data)
          var that = this
          if (data.data.is_set === '2'){
              that.setData({
                showPayPwdInput: true,
                payFocus: true,
                orderMoney: false,
                payModal: {
                  show: false,
                  pay: 'pay'
                }
              })
          }else{
            // 成功输入完密码后，调用此方法
            that.luck();
          }
        
        }
      )
    }
    //余额支付

    //微信支付
    if (payway === '5') {
      var that = this
      var url = 'Order_payOrder'
      // console.log(that.data.info.total_fee)
      // var total_fee = that.data.info.total_fee
      var token = wx.getStorageSync('token')
      console.log(token)
      var order_no = that.data.order_no
      console.log(order_no)
      var payway = that.data.payway
      console.log(payway)
      wx.login({
        success: function (res) {
          var code = res.code
          console.log(code)

          //请求支付
          http._post(
            url,
            { token: token, order_no: order_no, type: payway, code: code },
            res => {
              var data = res.data
              console.log(data)
              //判断是否为1
              if (data.re === '1') {
                //  var rinfo = data.data.rinfo
                //  console.log(data.data.rinfo)
                // var total_fee = that.data.info.total_fee
                // console.log(total_fee)
                let pay_config = data.data.rinfo.jsApiParameters
                console.log(pay_config)

                //调用微信支付接口
                wx.requestPayment({
                  appId: pay_config.appId,
                  timeStamp: pay_config.timeStamp,
                  nonceStr: pay_config.nonceStr,
                  package: pay_config.package,
                  signType: pay_config.signType,
                  paySign: pay_config.paySign,    //签名算法
                  success: function (res) {
                    console.log(res)
                    wx.navigateTo({
                      url: '/pages/course/soiDetail/soiDetailPay/soiDetailPaySuc/soiDetailPaySuc'
                    })
                  },
                  fail: function (res) {
                    console.log(res)
                    wx.showToast({
                      title: '用户取消支付',
                      icon: 'none',
                      duration: 3000,
                      success: function () {
                        that.hidePay()
                      }
                    })
                  }
                }) //微信支付接口调用完毕
              }//判断是否为1
            }
          )//请求支付
        }
      })
    }
    //微信支付
  },






    /**
     * 支付
     */
    // pay() {
    //     let that = this,
    //         url = 'Order_payOrder',
    //         token = wx.getStorageSync('token'),
    //         order_no = that.data.order_no,
    //         payway = that.data.payway


    //     wx.login({
    //         success: function (res) {
    //             let code = res.code

    //             http._post(
    //                 url,
    //                 { token: token, order_no: order_no, type: payway, code: code },
    //                 res => {
    //                     console.log(res.data)

    //                     let data = res.data
    //                     if (data.re === '1') {
    //                         if (payway === '5') {
    //                             let pay_config = data.data.rinfo.jsApiParameters
    //                             wx.requestPayment({
    //                                 // appId: pay_config.appid,
    //                                 // timeStamp: pay_config.timestamp,
    //                                 // nonceStr: pay_config.noncestr,
    //                                 // package: 'prepay_id=' + pay_config.prepayid,
    //                                 // signType: 'MD5',
    //                                 // paySign: pay_config.sign,
    //                                 appId: pay_config.appId,
    //                                 timeStamp: pay_config.timeStamp,
    //                                 nonceStr: pay_config.nonceStr,
    //                                 package: pay_config.package,
    //                                 signType: pay_config.signType,
    //                                 paySign: pay_config.paySign,
    //                                 success: function (res) {
    //                                     wx.navigateTo({
    //                                         url: '/pages/course/paySuc/paySuc',
    //                                     })
    //                                 },
    //                                 fail: function (res) {
    //                                     wx.showToast({
    //                                         title: '取消支付',
    //                                         icon: 'none',
    //                                         duration: 1000,
    //                                         success: function () {
    //                                             that.hidePay()
    //                                         }
    //                                     })
    //                                 }
    //                             })
    //                         } else {
    //                             wx.showToast({
    //                                 title: data.info,
    //                                 icon: 'none',
    //                                 duration: 1500,
    //                                 success: function () {
    //                                     setTimeout(function () {
    //                                         wx.navigateTo({
    //                                             url: '/pages/course/paySuc/paySuc',
    //                                         })
    //                                     }, 1500)
    //                                 }
    //                             })
    //                         }
    //                     } else {
    //                         wx.showToast({
    //                             title: data.info,
    //                             icon: 'none',
    //                             duration: 1000,
    //                             success: function () {
    //                                 that.hidePay()
    //                             }
    //                         })
    //                     }
    //                 },
    //                 err => {
    //                     console.log(err)
    //                 }
    //             )
    //         }
    //     })
    // },

    /**
     * 获取余额
     */
    getBalance() {
        let that = this,
            url = 'Ucenter_userMoney',
            token = wx.getStorageSync('token')

        http._post(
            url,
            { token: token },
            res => {
                // console.log(res.data)
                let data = res.data
                if (data.re === '1') {
                    that.setData({
                        balance: Number(data.data)
                    })
                } else {
                    that.setData({
                        balance: 0
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 获取订单列表
     */
    getList(p) {
        let that = this,
            url = 'Order_myOrder',
            token = wx.getStorageSync('token')
            console.log(p)
            console.log(url)
            console.log(token)
            http._post(
            url,
            { token: token, page: p ,type:-1},
            res => {
                console.log(res.data)

                let data = res.data
            console.log(data)
                if (data.re === '1') {
                    let temp_arr = that.data.star,
                        temp_list = that.data.order_list
                    for (let item of data.data.list) {
                        temp_arr.push(Number(item.star))
                        temp_list.push(item)
                    }

                    this.setData({
                        order_list: temp_list,
                        star: temp_arr,
                        is_page: data.data.is_page,
                        page: data.data.page,
                        sum_page: data.data.sum_page
                    })
                } else {
                    this.setData({
                        order_list: [],
                        star: [],
                        is_page: data.data.is_page,
                        page: data.data.page,
                        sum_page: data.data.sum_page
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 取消订单
     */
    cancelOrder(e) {
        let that = this,
            url = 'Order_cancelOrder',
            token = wx.getStorageSync('token'),
            id = http.dataIndex(e)[1]
        http._post(
            url,
            { token: token, order_id: id },
            res => {
                console.log(res.data)

                let data = res.data
                if (data.re === '1') {
                    wx.showToast({
                        title: data.info,
                        icon: 'none',
                        duration: 1000,
                        success: function() {
                        //     setTimeout(function(){
                        //       that.setData({
                        //         order_id: id
                        //       })
                        //       let page = that.data.page
                        //       that.getList(page)
                        //       let url = 'Order_myOrder'
                        //       http._post(
                        //         url,
                        //         { token: token, page: 0, type: -1},
                        //         res=>{
                        //           console.log(res)
                        //         }
                        //       )
                        //     },1000)
                           
                          
                            setTimeout(function () {
                                that.setData({
                                    order_list: [],
                                    star: [],
                                  order_id: id
                                })
                                let page = that.data.page
                                that.getList(page)
                                let url = 'Order_myOrder'

                                http._post(
                                    url,
                                    { token: token, page: 0,type:-1 },
                                    res => {
                                        // console.log(res.data)

                                        let data1 = res.data

                                        if (data1.re === '1') {
                                            let temp_arr = []
                                            for (let item of data1.data.list) {
                                                temp_arr.push(Number(item.star))
                                            }

                                            that.setData({
                                                order_list: data1.data.list,
                                                star: temp_arr,
                                                is_page: data1.data.is_page,
                                                page: data1.data.page,
                                                sum_page: data1.data.sum_page
                                            })
                                        } else {
                                            that.setData({
                                                order_list: [],
                                                star: [],
                                                is_page: data1.data.is_page,
                                                page: data1.data.page,
                                                sum_page: data1.data.sum_page
                                            })
                                        }
                                    },
                                    err => {
                                        console.log(err)
                                    }
                                )
                            }, 1000)
                        }
                    })
                } else {
                    wx.showToast({
                        title: data.info,
                        icon: 'none',
                        duration: 1000
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getBalance()  // 获取余额
       
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    // 点击前往商品详情
    navXqLcm(e){
        let id = http.dataIndex(e)[1];
        console.log(id)
        wx.navigateTo({
            url: '/pages/course/course?id=' + id,
        })
    },
    // 辅助资料详情
    navXqfdBtn(e){
        let id = http.dataIndex(e)[1];
        console.log(id)
        wx.navigateTo({
            url: '/pages/course/soiDetail/soiDetail?id=' + id,
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      this.getList(0)  // 获取订单列表
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        let that = this,
            is_page = that.data.is_page,
            page = that.data.page + 1

        if (is_page === '1') {
            that.getList(page)
        } else {
            wx.showToast({
                title: '已经没有了',
                icon: 'none',
                duration: 1000
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})